package opn.srn.command.excel;

import java.util.HashMap;
import java.util.Map;

import opn.srn.command.Command;
import opn.srn.command.ICommand;
import opn.srn.common.IMessage;
import opn.srn.event.EventConstants;
import opn.srn.event.IEvent;

import org.apache.poi.hssf.usermodel.HSSFWorkbook;
import org.apache.poi.ss.usermodel.Sheet;

public class ExcelCommand extends Command {

	public static final String NAME = "convertor";

	HSSFWorkbook workbook = new HSSFWorkbook();

	Sheet curSheet;
	int maxRowsPerSheet = 100000;
	int curRecordCount = 0;
	int curSheetNo = 1;

	Map<String, Integer> columnIndexes = new HashMap<String, Integer>();

	public ExcelCommand() {
		super(NAME);
	}

	@Override
	public void load(Map<String, String> parameters) throws Exception {
		String fieldList = parameters.get("fields");
		if (fieldList == null) {
			throw new Exception("fields parameter missing for convertor command...");
		}

	}

	@Override
	public void onEvent(ICommand<?> source, IEvent event) throws Exception {
		switch (event.getType()) {
		case EventConstants.CMD_START: {
			break;
		}
		case EventConstants.CMD_DATA: {
			Object data = event.getData();
			if (data instanceof IMessage) {
				populateNewRow((IMessage) data);
			}
			break;
		}
		case EventConstants.CMD_FINISH: {
			break;
		}
		}
		fireEvent(source, event);
	}

	private void populateNewRow(IMessage data) {
		if (curSheet == null) {
			curSheet = workbook.createSheet("Sheet" + curSheetNo);
		}
		
		if (maxRowsPerSheet != -1) {
			if (curRecordCount % maxRowsPerSheet == 0) {
				curRecordCount = 0;
				curSheetNo++;
			}
		} 
		
		curRecordCount++;
		
		curSheet.cre

	}
}
